﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Xml;
using EncryptHelper;

namespace WebHelper.Modules
{
    [Serializable]
    public class MyProtectedConfigurationProvider : ProtectedConfigurationProvider
    {

        // Performs provider initialization.
        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);
        }

        public override string Name
        {
            get
            {
                return typeof(MyProtectedConfigurationProvider).Name;
            }
        }

        // Performs encryption.
        public override XmlNode Encrypt(XmlNode node)
        {
            string encryptedData = DefaultEncryptHelper.Encrypt(node.OuterXml, WebHelper.Properties.Resources.Key);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml("<EncryptedData>" + HttpUtility.HtmlEncode(encryptedData) + "</EncryptedData>");
            
            //trace
            Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Encrypt : " + node.OuterXml + "---->" + HttpUtility.HtmlEncode(encryptedData), typeof(MyProtectedConfigurationProvider).Name + "  ");
            
            return xmlDoc.DocumentElement;
        }

        // Performs decryption.
        public override XmlNode Decrypt(XmlNode encryptedNode)
        {
            string decryptedData = DefaultEncryptHelper.Decrypt(HttpUtility.HtmlDecode(encryptedNode.InnerXml), WebHelper.Properties.Resources.Key);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(decryptedData);

            //trace
            Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "dycrpt : " + encryptedNode.InnerXml + "---->" + decryptedData, typeof(MyProtectedConfigurationProvider).Name + "  ");


            return xmlDoc.DocumentElement;
        }
    }

}
